<template>
    <div class="user-management">
        <div class="search-container">
            <el-input v-model="search" placeholder="请输入用户ID或姓名查询" clearable @clear="handleClearSearch"
                @keyup.enter.native="fetchUsers" class="search-input" />
            <el-button type="primary" @click="fetchUsers" class="search-button">搜索</el-button>

            <el-select v-model="selectedSex" placeholder="按性别筛选" clearable @change="fetchUsers" class="filter-select">
                <el-option label="全部" value="" />
                <el-option label="男" value="male" />
                <el-option label="女" value="female" />
            </el-select>
            <el-select v-model="selectedRole" placeholder="按角色筛选" clearable @change="fetchUsers" class="filter-select">
                <el-option label="全部" value="" />
                <el-option label="学生" value="student" />
                <el-option label="教师" value="teacher" />
                <el-option label="管理员" value="admin" />
            </el-select>
            <el-button type="primary" @click="openDialog('add')" class="add-button">新增用户</el-button>
        </div>

        <el-table :data="users" stripe border>
            <el-table-column prop="user_id" label="用户ID" />
            <el-table-column prop="name" label="姓名" />
            <el-table-column prop="role" label="角色">
                <template #default="{ row }">
                    <el-tag :type="roleTagType[row.role]">{{ roleMap[row.role] }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="sex" label="性别">
                <template #default="{ row }">
                    {{ sexMap[row.sex] }}
                </template>
            </el-table-column>
            <el-table-column label="密码">
                <template #default="{ row }">
                    <el-button size="small" type="primary" link @click="togglePasswordVisibility(row)">
                        {{ row.showPassword ? row.password : '*'.repeat(row.password?.length || 6) }}
                    </el-button>
                </template>
            </el-table-column>
            <el-table-column prop="borrow_limit" label="借阅上限" />
            <el-table-column prop="phone" label="手机号" />
            <el-table-column prop="email" label="邮箱" />
            <el-table-column prop="created_at" label="创建时间" />
            <el-table-column prop="updated_at" label="更新时间" />
            <el-table-column label="操作">
                <template #default="{ row }">
                    <el-button size="small" @click="openDialog('edit', row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination background layout="prev, pager, next" :total="total" :page-size="pageSize"
            v-model:current-page="currentPage" @current-change="fetchUsers" class="pagination" />

        <el-dialog :title="dialogTitle" v-model="dialogVisible" width="30%">
            <el-form :model="currentUser" :rules="rules" ref="form" label-width="100px">
                <el-form-item label="用户ID" prop="user_id">
                    <el-input v-model="currentUser.user_id" placeholder="请输入用户ID" :disabled="dialogType === 'edit'" />
                </el-form-item>
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="currentUser.name" placeholder="请输入姓名" />
                </el-form-item>
                <el-form-item label="密码" v-if="dialogType === 'edit'" prop="password">
                    <el-input v-model="currentUser.password" type="password" placeholder="请输入密码" />
                </el-form-item>
                <el-form-item label="借阅上限" prop="borrow_limit">
                    <el-input v-model="currentUser.borrow_limit" placeholder="请输入借阅上限" type="number" min="0" />
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                    <el-input v-model="currentUser.phone" placeholder="请输入手机号" />
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="currentUser.email" placeholder="请输入邮箱" />
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                    <el-select v-model="currentUser.sex" placeholder="请选择性别">
                        <el-option label="男" value="male" />
                        <el-option label="女" value="female" />
                    </el-select>
                </el-form-item>
            </el-form>
            <div class="dialog-footer" slot="footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSave">确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { userApi } from '@/request/apiService';
import { ElMessageBox } from 'element-plus';

// 数据状态
const users = ref([]);
const currentUser = ref({
    user_id: '',
    name: '',
    role: '',
    borrow_limit: 0,
    phone: '',
    email: '',
    sex: '',
    password: '', // 仅在编辑时可用
});
const form = ref(null); // 绑定 el-form 的 ref
const dialogVisible = ref(false);
const search = ref('');
const selectedSex = ref(''); // 性别筛选
const selectedRole = ref(''); // 角色筛选
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const dialogTitle = ref('');
const dialogType = ref('add'); // add 或 edit

const roleMap = { student: '学生', teacher: '教师', admin: '管理员' };
const roleTagType = { student: 'info', teacher: 'success', admin: 'danger' };
const sexMap = { male: '男', female: '女' }; // 性别映射

// 表单验证规则
const rules = {
    user_id: [{ required: true, message: '请输入用户ID', trigger: 'blur' }],
    name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    password: [{ required: dialogType.value === 'add', message: '请输入密码', trigger: 'blur' }],
    borrow_limit: [{ required: true, message: '请输入借阅上限', trigger: 'blur' }],
    phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
    email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' },
    ],
    sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
};

// 获取用户列表
const fetchUsers = async () => {
    const params = {
        page: currentPage.value,
        pageSize: pageSize.value,
        search: search.value.trim() || undefined,
        sex: selectedSex.value || undefined, // 如果为空，传递 undefined
        role: selectedRole.value || undefined, // 如果为空，传递 undefined
    };
    const response = await userApi.getUserList(params);
    users.value = response.data.map(user => ({ ...user, showPassword: false }));
    total.value = response.total;
};

// 清空搜索框
const handleClearSearch = () => {
    search.value = '';
    selectedSex.value = '';
    selectedRole.value = '';
    fetchUsers();
};

// 打开对话框
const openDialog = (type, user = {}) => {
    dialogType.value = type;
    dialogTitle.value = type === 'add' ? '新增用户' : '编辑用户';
    if (type === 'add') {
        currentUser.value = {
            user_id: '',
            name: '',
            role: '',
            borrow_limit: 0,
            phone: '',
            email: '',
            sex: '',
            password: '',
        };
    } else {
        currentUser.value = { ...user };
    }
    dialogVisible.value = true;
};

// 保存用户（新增或更新）
const handleSave = () => {
    if (!form.value) return; // 检查 form 是否正确绑定
    form.value.validate(async (valid) => {
        if (!valid) return; // 表单校验未通过，直接退出
        if (dialogType.value === 'add') {
            await userApi.addUser(currentUser.value);
        } else {
            await userApi.updateUser(currentUser.value);
        }
        await fetchUsers();
        dialogVisible.value = false;
    });
};

// 删除用户
const handleDelete = (user) => {
    ElMessageBox.confirm('此操作将永久删除该用户, 是否继续?', '警告', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(async () => {
            await userApi.deleteUser({ user_id: user.user_id });
            await fetchUsers();
        })
        .catch(() => {
            // 用户取消删除
        });
};

// 切换密码显示
const togglePasswordVisibility = (row) => {
    row.showPassword = !row.showPassword;
};

// 页面加载时，获取用户数据
onMounted(fetchUsers);
</script>

<style scoped>
.user-management {
    padding: 20px;
}

.search-container {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    flex-wrap: wrap;
}

.search-input {
    width: 300px;
    margin-right: 10px;
}

.search-button {
    margin-right: 20px;
}

.filter-select {
    margin-right: 20px;
    width: 150px;
}

.add-button {
    margin-top: 10px;
}

.pagination {
    margin-top: 20px;
    text-align: center;
}

.dialog-footer {
    text-align: right;
}
</style>
